package com.besmart.workflow.core.service.factory.extractor;

import java.util.Iterator;
import java.util.List;

import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.besmart.workflow.core.exception.ConditionExtractException;
import com.besmart.workflow.core.exception.OperationNodeExtractException;
import com.besmart.workflow.core.exception.WorkflowNodeExtractException;
import com.besmart.workflow.core.model.Constants;
import com.besmart.workflow.core.model.OperationNode;
import com.besmart.workflow.core.model.WorkflowNode;

@Service
public class WorkflowNodeExtractor {
	
	private static final String INVALID_WORKFLOW_NODE_NAME_MESSAGE = "Invalid element name in the xml file, please make sure the node name is: workflow";
	@Autowired
	private OperationNodeExtractor extractor;

	public WorkflowNode extract(Element workflowElementNode) throws WorkflowNodeExtractException, OperationNodeExtractException, ConditionExtractException
	{
		if(workflowElementNode.getName().equals(Constants.WORKFLOW_NODE_NAME))
		{
			String id = workflowElementNode.attributeValue(Constants.WORKFLOW_NODE_ID);
			WorkflowNode workflowNode = new WorkflowNode(id);
			insertOperationNodes(workflowElementNode, workflowNode);
			return workflowNode;
		}
		else
		{
			throw new WorkflowNodeExtractException(INVALID_WORKFLOW_NODE_NAME_MESSAGE);
		}
	}
	
	private void insertOperationNodes(Element workflowElementNode,WorkflowNode workflowNode) throws OperationNodeExtractException, ConditionExtractException {
		List<?> elementNodes = workflowElementNode.selectNodes(Constants.OPERATION_NAME);
		Iterator<?> iter = elementNodes.iterator();
		while(iter.hasNext())
		{
			Element operationElementNode = (Element) iter.next();
			OperationNode operationNode = extractor.extract(operationElementNode);
			workflowNode.addOperation(operationNode);
		}
	}

}
